package com.cbts.util;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {

	/**
	 * @param sendContext
	 *            发送内容
	 * @param Subject
	 *            发送标题
	 * @param recEmail
	 *            接收人邮箱
	 */
	public boolean sendTxtMail(String sendContext, String Subject,
			String recEmail) {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.163.com"); // smtp服务器地址

		props.put("mail.smtp.auth", "true"); // 是否需要认证

		/**
		 * 实例化一个验证里，继承abstract Authenticator 实现 protected PasswordAuthentication
		 * getPasswordAuthentication(){ return new
		 * PasswordAuthentication(userName,password); }
		 */
		MyAuthenticator myauth = new MyAuthenticator("zhenglinglynn@163.com",
				"hkgpukkepwtftxrd");
		// 获得一个带有authenticator的session实例
		Session session = Session.getInstance(props, myauth);
		session.setDebug(true);// 打开debug模式，会打印发送细节到console
		Message message = new MimeMessage(session); // 实例化一个MimeMessage集成自abstract
													// Message 。参数为session
		try {
			message.setFrom(new InternetAddress("zhenglinglynn@163.com")); // 设置发出方,使用setXXX设置单用户，使用addXXX添加InternetAddress[]
			message.setText(sendContext); // 设置文本内容
											// 单一文本使用setText,Multipart复杂对象使用setContent

			message.setSubject(Subject); // 设置标题
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					recEmail)); // 设置接收方
			Transport.send(message); // 使用Transport静态方法发送邮件
			return true;

		} catch (AddressException e) {
			// 此处处理AddressException异常 [The exception thrown when a wrongly
			// formatted address is encountered.]
			return false;
		} catch (MessagingException e) {
			// 此处处理MessagingException异常 [The base class for all exceptions
			// thrown by the Messaging classes ]
			return false;
		}

	}
}
